package com.example.smartwaterapi.service.impl;

import com.example.smartwaterapi.service.TemplateMessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 微信公众号模板消息服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateMessageServiceImpl implements TemplateMessageService {

    @Autowired
    private WxMpService wxMpService;

    /**
     * 异步发送微信模板消息
     */
    @Override
    @Async
    public void sendTemplateMessage(WxMpTemplateMessage msg, String appid) {
        try {
            // 切换到指定的公众号配置
            wxMpService.switchover(appid);
            
            // 发送模板消息
            String result = wxMpService.getTemplateMsgService().sendTemplateMsg(msg);
            
            log.info("微信模板消息发送成功: toUser={}, templateId={}, result={}", 
                    msg.getToUser(), msg.getTemplateId(), result);
                    
        } catch (WxErrorException e) {
            log.error("微信模板消息发送失败: toUser={}, templateId={}, errorCode={}, errorMsg={}", 
                    msg.getToUser(), msg.getTemplateId(), e.getError().getErrorCode(), e.getError().getErrorMsg());
        } catch (Exception e) {
            log.error("微信模板消息发送异常: toUser={}, templateId={}", msg.getToUser(), msg.getTemplateId(), e);
        }
    }
} 